package com.tywj.lib.lifecycle.extension

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.tywj.lib.core.common.extension.safeDisposable
import io.reactivex.disposables.Disposable
import java.lang.IllegalStateException

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/8
 *     desc   : 能根据生命周期变化自动取消订阅的Disposable
 *     version: 1.0.0
 * </pre>
 */
class LifecycleDisposable(
    private val disposable: Disposable,
    owner: LifecycleOwner,
    private val untilEvent: Lifecycle.Event = Lifecycle.Event.ON_DESTROY
) : DefaultLifecycleObserver {

    init {
        if (owner.lifecycle.currentState == Lifecycle.State.DESTROYED) {
            throw IllegalStateException("Lifecycle has destroyed!")
        }
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        if (untilEvent == Lifecycle.Event.ON_PAUSE) {
            disposable.safeDisposable()
        }
    }


    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)

        if (untilEvent == Lifecycle.Event.ON_STOP) {
            disposable.safeDisposable()
        }
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        // when currentEvent is ON_DESTROY, No matter what untilEvent is, it must dispose,
        // avoid like create this class after ON_PAUSE, but untilEvent is ON_PAUSE, it maybe cause the memory leak.
        disposable.safeDisposable()
    }
}